//
//  WSImageTag.m
//  WSComponent
//
//  Created by lienbao on 15/09/2014.
//  Copyright (c) 2014 Lienbao. All rights reserved.
//

#import "WSImageTag.h"
#import "UIComponent.h"

@interface WSImageTag ()

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *titleLabel;

@end

@implementation WSImageTag

- (id)initWithFrame:(CGRect)frame image:(UIImage *)image title:(NSString *)title
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.height, self.height)];
        [self addSubview:_imageView];
        
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.height, 0, self.width - self.height, self.height)];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont systemFontOfSize:13.0f];
        [self addSubview:_titleLabel];
        [self setImage:image title:title];
    }
    return self;
}

- (void)setImage:(UIImage *)image title:(NSString *)title
{
    _imageView.image = image;
    _titleLabel.text = title;
    [self resizeConstrainedToSize:CGSizeMake(1000, 0)];
}

- (void)resizeConstrainedToSize:(CGSize)size
{
    CGSize  imageSize = _imageView.image.size;
    if (!imageSize.width || !imageSize.height) {
        return;
    }
    
    CGFloat height = imageSize.height > self.height ? self.height:imageSize.height;
    CGFloat width  = imageSize.width * (height/imageSize.height);
    _imageView.frame = CGRectMake(0, (self.height - height)/2, width, height);
    
    CGSize titleSize = [_titleLabel.text rtSizeWithFont:_titleLabel.font];
    _titleLabel.left = _imageView.right;
    _titleLabel.right = (titleSize.width + _titleLabel.left) > size.width ? titleSize.width:(size.width - _titleLabel.left);
}

@end
